package com.shanghai.market.plshnaghai.utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;

import com.shanghai.market.plshnaghai.AppApplication;

import org.apache.http.util.EncodingUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

/**
 * 文件处理类
 * 
 * @author bill
 */
public class FileUtils {

	public static boolean exist(String paramString) {
		return new File(paramString).exists();
	}

	public static boolean exist(Uri paramUri) {

		ContentResolver localContentResolver = AppApplication.getInstance().getContentResolver();
		try {
			localContentResolver.openFileDescriptor(paramUri, "r");
			return true;
		} catch (FileNotFoundException ex) {
			ex.printStackTrace();
		}
		return false;
	}

	public static ParcelFileDescriptor getParcelFileDescriptorFromUri(Uri paramUri)
			throws FileNotFoundException {
		return AppApplication.getInstance().getContentResolver().openFileDescriptor(paramUri, "r");
	}

	public static long getFileSize(String paramString) {
		if (TextUtils.isEmpty(paramString))
			return 0L;
		return new File(paramString).length();
	}

	public static boolean deleteDirectory(File paramFile) {
		if (paramFile.exists()) {
			File[] arrayOfFile = paramFile.listFiles();
			if (arrayOfFile != null) {
				int i = arrayOfFile.length;
				for (int j = 0; j < i; j++)
					deleteDirectory(arrayOfFile[j]);
			}
		}
		return deleteFile(paramFile);
	}

	public static boolean deleteDirectory(String paramString) {
		return deleteDirectory(new File(paramString));
	}

	public static boolean deleteFile(File paramFile) {
		if (paramFile.exists()) {
			return paramFile.delete();
		}
		return true;
	}

	public static boolean deleteFile(String paramString) {
		File paramFile = new File(paramString);
		return deleteFile(paramFile);
	}

	/**
	 * 保存到文件
	 * 
	 * @param paramString
	 *            文件的绝对路径（包括文件名）
	 * @param arrayOfBytes
	 *            需要保存的字节数组
	 * @throws IOException
	 */
	public static void saveToFile(String pathName, byte[] arrayOfBytes) throws IOException {
		if (arrayOfBytes != null) {
			File localFile = new File(pathName);
			if (localFile.exists())
				localFile.delete();
			createNewFile(localFile);
			FileOutputStream localFileOutputStream = new FileOutputStream(localFile);
			localFileOutputStream.write(arrayOfBytes);
			localFileOutputStream.flush();
			localFileOutputStream.close();
		}
	}

	public static void saveToFile(String pathName, String content) throws IOException {
		saveToFile(pathName, content.getBytes());
	}

	public static boolean createNewFile(File paramFile) throws IOException {
		File localFile = paramFile.getParentFile();
		if (localFile != null && !localFile.isDirectory()) {
			localFile.delete();
			localFile.mkdirs();
		}
		return paramFile.createNewFile();
	}

	public static String getFilePahtFromUri(Uri paramUri) {
		if (paramUri.toString().startsWith("content")) {
			ContentResolver contentResolver = AppApplication.getInstance().getContentResolver();
			String[] arrayOfString = { "_data" };
			Cursor cursor = null;
			try {
				cursor = contentResolver.query(paramUri, arrayOfString, null, null, null);
				if (cursor.moveToFirst()) {
					return cursor.getString(cursor.getColumnIndexOrThrow("_data"));
				}
				return getFilePathFromUrl(paramUri.toString());
			} finally {
				if (cursor != null)
					cursor.close();
			}
		}
		return (String) getFilePathFromUrl(paramUri.toString());
	}

	@SuppressWarnings("deprecation")
	private static String getFilePathFromUrl(String paramString) {
		if ((TextUtils.isEmpty(paramString)) || (!paramString.startsWith("file://")))
			return null;
		return URLDecoder.decode(paramString).replaceAll("^file://", "");
	}

	/**
	 * 获取文件的名字后缀
	 * 
	 * @param fileName
	 *            文件名字
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	private static String getSuffix(String fileName) {
		int i = fileName.lastIndexOf(".");
		if (i > 0)
			return fileName.substring(i + 1).toLowerCase();
		return "";
	}

	public static boolean mkdir(String paramString) throws IOException {
		if (TextUtils.isEmpty(paramString))
			return false;
		boolean bool = true;
		File localFile = new File(paramString);
		if (!localFile.exists())
			bool = localFile.mkdirs();
		return bool;
	}

	/**
	 * 从asset中获取文件并读取数据
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFromAsset(String fileName) {
		String result = "";
		try {
			InputStream in = AppApplication.getInstance().getResources().getAssets().open(fileName); // 从Assets中的文件获取输入流
			int length = in.available(); // 获取文件的字节数
			byte[] buffer = new byte[length]; // 创建byte数组
			in.read(buffer); // 将文件中的数据读取到byte数组中
			result = EncodingUtils.getString(buffer, "utf-8"); // 将byte数组转换成指定格式的字符串
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
